package com.example.musicaiap.navigation

import android.util.Log
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
// Removed the block of duplicate imports below
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.util.UnstableApi
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.musicaiap.ui.about.AboutScreen // Import AboutScreen
import com.example.musicaiap.ui.main.MainViewModel // Import MainViewModel
import com.example.musicaiap.ui.community.CommunityViewModel
import com.example.musicaiap.ui.home.HomeScreen
import com.example.musicaiap.ui.player.PlayerScreen
import com.example.musicaiap.ui.player.PlayerViewModel
import com.example.musicaiap.ui.playlist.PlaylistScreen

/**
 * 页面导航状态
 * 用于在不同页面间共享导航相关状态，特别是动画状态
 */
class NavigationState {
    // 记录当前是否在播放列表页面
    var isInPlaylistScreen by mutableStateOf(false)
        private set

    // 存储选中的导航项，以便从PlayerScreen返回时恢复
    var lastSelectedTabIndex by mutableStateOf(0)

    // 更新当前页面状态
    fun updateCurrentScreen(route: String?) {
        isInPlaylistScreen = route?.startsWith("playlist/") == true
    }
}

/**
 * 应用中的屏幕路由
 * 定义应用内所有可导航的屏幕
 */
sealed class Screen(val route: String) {
    /**
     * 首页
     * 应用启动后的默认页面
     */
    object Home : Screen("home")

    /**
     * 播放列表详情页
     * 显示特定播放列表的歌曲
     * 路径包含playlistId参数
     */
    object Playlist : Screen("playlist/{playlistId}") {
        /**
         * 创建带有播放列表ID的路由路径
         * @param playlistId 播放列表ID
         * @return 格式化后的路由路径
         */
        fun createRoute(playlistId: String) = "playlist/$playlistId"
    }

    /**
     * 播放器页面
     * 显示全屏播放器界面
     */
    object Player : Screen("player")

    /**
     * 关于页面
     * 显示应用信息
     */
    object About : Screen("about")
}

/**
 * 导航动作
 * 包装导航控制器，提供便捷的页面导航方法
 * @param navController 导航控制器
 */
class AppNavigationActions(private val navController: NavHostController) {

    /**
     * 导航到主页
     * 会清除回退栈，避免导航循环
     */
    fun navigateToHome() {
        navController.navigate(Screen.Home.route) {
            // 清除回退栈，避免导航循环
            popUpTo(Screen.Home.route) {
                inclusive = true
            }
        }
    }

    /**
     * 导航到播放列表页面
     * @param playlistId 要查看的播放列表ID
     */
    fun navigateToPlaylist(playlistId: String) {
        navController.navigate(Screen.Playlist.createRoute(playlistId))
    }

    /**
     * 导航到播放器页面
     * 显示全屏播放器UI
     */
    fun navigateToPlayer() {
        navController.navigate(Screen.Player.route)
    }

    /**
     * 导航到关于页面
     */
    fun navigateToAbout() {
        navController.navigate(Screen.About.route)
    }

    /**
     * 返回上一屏幕
     * 调用popBackStack执行回退操作
     */
    fun navigateBack() {
        navController.popBackStack()
    }
}

/**
 * 应用的主要导航图
 * 设置整个应用的导航结构，配置各个屏幕和它们之间的跳转关系
 *
 * @param navController 导航控制器，默认创建一个新的
 * @param onPermissionRequest 权限请求回调，用于处理权限请求
 * @param navigationState 导航状态，用于在页面间共享状态
 * @param mainViewModel 主ViewModel实例，用于共享全局状态
 */
@UnstableApi
@Composable
fun AppNavigation(
    navController: NavHostController = rememberNavController(),
    onPermissionRequest: ((Boolean) -> Unit) -> Unit,
    navigationState: NavigationState = remember { NavigationState() },
    mainViewModel: MainViewModel, // Add MainViewModel parameter
    startDestination: String = Screen.Home.route
) {
    val TAG = "AppNavigation"
    val navigationActions = remember(navController) {
        AppNavigationActions(navController)
    }

    // 获取当前导航路由
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route

    // 当路由变化时更新导航状态
    LaunchedEffect(currentRoute) {
        navigationState.updateCurrentScreen(currentRoute)
    }

    // 应用的导航图配置，添加页面间过渡动画
    NavHost(
        navController = navController,
        startDestination = startDestination
    ) {
        // 首页
        composable(
            route = Screen.Home.route,
            enterTransition = {
                // 从播放列表返回首页
                if (initialState.destination.route?.startsWith("playlist/") == true) {
                    fadeIn(animationSpec = tween(300)) +
                    slideInHorizontally(
                        initialOffsetX = { -300 },
                        animationSpec = tween(300)
                    )
                } else {
                    fadeIn(animationSpec = tween(300))
                }
            },
            exitTransition = {
                // 进入播放列表时的过渡
                if (targetState.destination.route?.startsWith("playlist/") == true) {
                    fadeOut(animationSpec = tween(300)) +
                    slideOutHorizontally(
                        targetOffsetX = { -300 },
                        animationSpec = tween(300)
                    )
                } else {
                    fadeOut(animationSpec = tween(300))
                }
            }
        ) {
            HomeScreen(
                onPlaylistClick = { navigationActions.navigateToPlaylist(it) },
                onPlayerClick = { navigationActions.navigateToPlayer() },
                onPermissionResult = { callback ->
                    // 直接传递权限回调函数到MainActivity
                    Log.d(TAG, "权限请求向MainActivity传递")
                    onPermissionRequest(callback)
                },
                navigationState = navigationState,
                onNavigateToAbout = navigationActions::navigateToAbout // Pass the navigation action
            )
        }

        // 播放列表详情页
        composable(
            route = Screen.Playlist.route,
            enterTransition = {
                // 从首页进入播放列表
                fadeIn(animationSpec = tween(300)) +
                slideInHorizontally(
                    initialOffsetX = { 300 },
                    animationSpec = tween(300)
                )
            },
            exitTransition = {
                // 从播放列表返回首页
                fadeOut(animationSpec = tween(300)) +
                slideOutHorizontally(
                    targetOffsetX = { 300 },
                    animationSpec = tween(300)
                )
            }
        ) { backStackEntry ->
            val playlistId = backStackEntry.arguments?.getString("playlistId") ?: ""
            PlaylistScreen(
                playlistId = playlistId,
                onBackClick = navigationActions::navigateBack,
                onPlayerClick = navigationActions::navigateToPlayer,
                navigationState = navigationState
            )
        }

        // 播放器页面
        composable(Screen.Player.route) {
            // PlayerScreen might need its own ViewModel, keep hiltViewModel here if needed
            // val playerViewModel: PlayerViewModel = hiltViewModel()

            PlayerScreen(
                onNavigateBack = {
                    navController.navigateUp()
                    // 返回上一级，NavigationState中的lastSelectedTabIndex将保持不变
                },
                onNavigateToPlaylist = {
                    // 获取当前播放列表ID，如果没有则导航到"我喜欢"播放列表
                    val currentPlaylistId = "favorites" // 这里应该从PlayerController获取当前播放列表ID
                    navController.navigate(Screen.Playlist.createRoute(currentPlaylistId))
                }
                // Pass PlayerViewModel if needed: viewModel = playerViewModel
            )
        }

        // 关于页面
        composable(Screen.About.route) {
            AboutScreen(
                onNavigateBack = navigationActions::navigateBack,
                mainViewModel = mainViewModel // Pass the ViewModel instance
            )
        }
    }
}
